package cn.stylefeng.guns.modular.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.modular.business.pojo.AttendanceRecord;
import cn.stylefeng.guns.modular.business.mapper.AttendanceRecordMapper;
import cn.stylefeng.guns.modular.business.enums.StatusFlagEnum;
import cn.stylefeng.guns.modular.business.entity.AttendanceRecordRequest;
import cn.stylefeng.guns.modular.business.service.AttendanceRecordService;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.system.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class AttendanceRecordServiceImpl extends ServiceImpl<AttendanceRecordMapper, AttendanceRecord> implements AttendanceRecordService {

    @Resource
    SysUserService sysUserService;

    @Override
    public void add(AttendanceRecordRequest attendanceRecordRequest) {
        AttendanceRecord record = new AttendanceRecord();
        BeanUtil.copyProperties(attendanceRecordRequest, record);
        this.save(record);
    }

    @Override
    public PageResult<AttendanceRecord> findPage(AttendanceRecordRequest attendanceRecordRequest) {
        LambdaQueryWrapper<AttendanceRecord> wrapper = this.createWrapper(attendanceRecordRequest);

        Page<AttendanceRecord> page = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public boolean attend(LoginUser loginUser) {
        //当前登录用户
        SysUser sysUser = sysUserService.getById(loginUser.getUserId());
        //时间格式化
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = dateFormat.format(new Date());

        //查询当前打卡记录
        AttendanceRecordRequest recordRequest = new AttendanceRecordRequest();
        recordRequest.setUserId(sysUser.getUserId());
        recordRequest.setAttendanceDay(date);
        LambdaQueryWrapper<AttendanceRecord> wrapper = createWrapper(recordRequest);
        List<AttendanceRecord> list = this.list(wrapper);

        //打卡记录为空，创建打卡记录
        if (CollectionUtil.isEmpty(list)) {
            AttendanceRecord record = new AttendanceRecord();
            record.setUserId(sysUser.getUserId());
            record.setRealName(sysUser.getRealName());
            record.setNickName(sysUser.getNickName());
            record.setAccount(sysUser.getAccount());
            record.setAttendanceDay(date);
            record.setStartTime(new Date());
            record.setStatusFlag(StatusFlagEnum.ABNORMAL);
            this.save(record);
            return true;
        } else {
            //打卡记录不为空，修改下班时间
            AttendanceRecord attendanceRecord = list.get(0);
            AttendanceRecord update = new AttendanceRecord();
            update.setRecordId(attendanceRecord.getRecordId());
            update.setEndTime(new Date());
            update.setStatusFlag(StatusFlagEnum.NORMAL);
            update.setUpdateTime(new Date());
            this.updateById(update);
            return true;
        }
    }

    @Override
    public boolean abnormal(Long recordId) {
        if (recordId == null) {
            return false;
        }
        AttendanceRecord update = new AttendanceRecord();
        update.setRecordId(recordId);
        update.setStatusFlag(StatusFlagEnum.ABNORMAL);
        update.setUpdateTime(new Date());
        this.updateById(update);
        return true;
    }

    /**
     * 创建查询sql
     * @param attendanceRecordRequest 请求参数
     * @return sql查询对象
     */
    private LambdaQueryWrapper<AttendanceRecord> createWrapper(AttendanceRecordRequest attendanceRecordRequest) {
        LambdaQueryWrapper<AttendanceRecord> queryWrapper = new LambdaQueryWrapper<>();

        // 根据排序升序排列，序号越小越在前
        queryWrapper.orderByAsc(AttendanceRecord::getRecordId);

        if (ObjectUtil.isEmpty(attendanceRecordRequest)) {
            return queryWrapper;
        }

        //根据账号和开始结束时间进行查询
        String account = attendanceRecordRequest.getAccount();
        Date startTime = attendanceRecordRequest.getStartTime();
        Date endTime = attendanceRecordRequest.getEndTime();
        Long userId = attendanceRecordRequest.getUserId();
        String attendanceDay = attendanceRecordRequest.getAttendanceDay();

        // SQL条件拼接
        queryWrapper.eq(!StringUtils.isEmpty(account), AttendanceRecord::getAccount, account);
        queryWrapper.eq(!StringUtils.isEmpty(attendanceDay), AttendanceRecord::getAttendanceDay, attendanceDay);
        queryWrapper.eq(ObjectUtil.isNotNull(userId), AttendanceRecord::getUserId, userId);
        queryWrapper.ge(ObjectUtil.isNotNull(startTime), AttendanceRecord::getStartTime, startTime);
        queryWrapper.lt(ObjectUtil.isNotNull(endTime), AttendanceRecord::getEndTime, endTime);

        return queryWrapper;
    }
}
